package com.tarena.lbs.user.service.impl;

import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.common.enums.Roles;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.user.base.enums.UserGroupResultEnum;
import com.tarena.lbs.user.dao.repository.AdminRepository;
import com.tarena.lbs.user.dao.repository.UserGroupRepository;
import com.tarena.lbs.user.pojo.param.UserGroupParam;
import com.tarena.lbs.user.pojo.po.AdminPO;
import com.tarena.lbs.user.pojo.po.UserGroupPO;
import com.tarena.lbs.user.pojo.query.UserGroupQuery;
import com.tarena.lbs.user.pojo.vo.UserGroupVO;
import com.tarena.lbs.user.service.UserGroupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class UserGroupServiceImpl implements UserGroupService {
    @Autowired
    private UserGroupRepository userGroupRepository;
    @Autowired
    private AdminRepository adminRepository;

    @Override
    public PageResult<UserGroupVO> pageList(UserGroupQuery query) throws BusinessException {
        // 从 threadLocal 中获取用户id
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        if (userPrinciple == null){
            throw new BusinessException(UserGroupResultEnum.USER_NOT_LOGIN);
        }
        Integer adminUserId = userPrinciple.getId();
        log.debug("分页查询用户人群数据业务,adminUserId={}", adminUserId);
        // 通过用户 id 获取用户信息
        AdminPO adminPO = adminRepository.getAdminById(adminUserId);
        if (adminPO == null) {
            throw new BusinessException(UserGroupResultEnum.USER_NOT_EXIST);
        }
        // 获取商家id
        Integer businessId = adminPO.getBusinessId();
        // 通过商家 id 获取用户组信息
        PageInfo<UserGroupPO> pageInfo = userGroupRepository.pageList(query, businessId);
        PageResult<UserGroupVO> pageVO = new PageResult<>();
        //pageNo pageSize total
        // 将分页信息中的页码设置到分页结果对象中
        pageVO.setPageNo(pageInfo.getPageNum());
        // 将分页信息中的每页数量设置到分页结果对象中
        pageVO.setPageSize(pageInfo.getPageSize());
        // 将分页信息中的总记录数设置到分页结果对象中
        pageVO.setTotal(pageInfo.getTotal());
        List<UserGroupPO> pos = pageInfo.getList();
        List<UserGroupVO> vos = null;
        if (!CollectionUtils.isEmpty(pos)){
            vos = new ArrayList<>();
            for (UserGroupPO po : pos) {
                UserGroupVO vo = new UserGroupVO();
                BeanUtils.copyProperties(po, vo);
                vos.add(vo);
            }
        }
        pageVO.setObjects(vos);
        log.debug("分页查询用户人群数据业务,出参:vos={}", vos);
        return pageVO;
    }

    @Override
    public void saveGroup(UserGroupParam param) throws BusinessException {
        // 从 threadLocal 中获取用户id
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        if (userPrinciple == null){
            throw new BusinessException(UserGroupResultEnum.USER_NOT_LOGIN);
        }
        Integer userId = userPrinciple.getId();
        log.debug("保存用户人群数据业务,userId:{}", userId);
        // 检验用户权限
        Roles role = userPrinciple.getRole();
        if (role != Roles.SHOP) {
            throw new BusinessException(UserGroupResultEnum.USER_NOT_BUSINESS);
        }
        // 通过用户 id 获取用户信息
        AdminPO adminPO = adminRepository.getAdminById(userId);
        if (adminPO == null) {
            throw new BusinessException(UserGroupResultEnum.USER_NOT_EXIST);
        }
        if (param != null && param.getId() != null) {
            UserGroupPO userGroupPO = userGroupRepository.getById(param.getId());
            if (userGroupPO == null) {
                throw new BusinessException(UserGroupResultEnum.USER_GROUP_NOT_EXIST);
            }
            // 检验用户是否是该用户人群的创建人
            if (!userGroupPO.getBusinessId().equals(adminPO.getBusinessId())) {
                throw new BusinessException(UserGroupResultEnum.USER_NOT_BUSINESS);
            }
            userGroupRepository.updateById(param);
        } else if (param != null) {
            UserGroupPO userGroupPO = new UserGroupPO();
            BeanUtils.copyProperties(param, userGroupPO);
            userGroupPO.setCreateAt(new Date());
            userGroupPO.setBusinessId(adminPO.getBusinessId());
            log.debug("保存用户人群数据业务,userGroupPO:{}", userGroupPO);
            userGroupRepository.insert(userGroupPO);
        }
    }

    @Override
    public UserGroupVO detail(Integer id) {
        UserGroupPO userGroupPO = userGroupRepository.getById(id);
        UserGroupVO vo = new UserGroupVO();
        BeanUtils.copyProperties(userGroupPO, vo);
        return vo;
    }
}